//app.js
App({
    onLaunch: function () {
        let that = this
        //检测是否有新版本
        that.checkUpldate()
    },
    globalData: {
        urllbh: 'https://lbh-dev-service.hiworld.com/',
        upurl: 'https://service.hiworld.com/',
        url: 'https://ygz.service.ntest.cn/',
        jscode: null,
        encryptedData: null,
        iv: null,
        userInfo: null,
        showAuth: false,
        versions: 1.0,
        user_id:null,
        activity_id: 0,
        user_video_id: 0,
        video_id: 0,
        uploadToken:null
    },
    //登录
    wxLogin(cb){
        wx.login({
            success: res => {
                cb(res.code)
            }
        })
    },
    //点赞数转化为K
    numChange(num) {
        let fs = (num / 1000).toFixed(2).toString()
        if (fs.split('.')[1] == '00') {
            fs = fs.split('.')[0]
        }
        fs = fs + 'K'
        return fs
    },
    //检测是否有新版本
    checkUpldate(){
        const useUpdateManager = wx.canIUse('getUpdateManager')
        if (useUpdateManager) {
            const updateManager = wx.getUpdateManager()
            updateManager.onCheckForUpdate(function (res) {
                // 请求完新版本信息的回调

                console.log(res.hasUpdate)
            })

            updateManager.onUpdateReady(function () {
                wx.showModal({
                    title: '更新提示',
                    content: '新版本已经准备好，是否重启应用？',
                    showCancel: false,
                    success: function (res) {
                        if (res.confirm) {
                            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                            updateManager.applyUpdate()
                        }
                    }
                })

            })

            updateManager.onUpdateFailed(function () {
                // 新的版本下载失败
                wx.showModal({
                    title: '更新提示',
                    content: '新版本下载失败',
                    showCancel: false
                })
            })
        } else {
            // 微信版本过低
            wx.showModal({
                title: '更新提示',
                content: '您的微信版本过低，可能导致小程序无法使用，请升级微信！',
                showCancel: false
            })
        }
    },
    //ajax请求封装
    ajax(model) {
        wx.showLoading({
            title: '加载中',
        })
        model.data.p = this.globalData.versions
        //拼接url
        model.url = this.globalData.url + model.url
        if (model.data.sign) {
            model.url = model.url + "?sign=" + model.data.sign
            delete model.data.sign
        }
        //get参数拼接
        if (model.method == "GET" && model.data !== undefined) {
            let queryStr = '';
            for (let k in model.data) {
                if (model.data[k].toString() !== '') {
                    queryStr = queryStr + "&" + k + "=" + model.data[k];
                }
            }
            if (model.url.indexOf('?') < 0) {
                queryStr = "?" + queryStr.slice(1)
            }
            model.url = model.url + queryStr
            model.data = '';
        }
        let header = {
            'content-type': 'application/json'
        }
        if (model.method == "POST") {
            header = {
                'content-type': 'application/x-www-form-urlencoded'
            }
        }
        //返回Promise对象
        return new Promise(
            function (resolve) {
                wx.request({
                    method: model.method,
                    url: model.url,
                    data: model.data,
                    header: header,
                    success: (res) => {
                        if (res.statusCode == 200) {
                            resolve(res);
                        } else {
                            wx.showModal({
                                title: '温馨提示',
                                content: '服务器错误，稍后再试',
                                showCancel: false,
                            })
                        }
                    },
                    fail: () => {
                        wx.showModal({
                            title: '温馨提示',
                            content: '服务器错误，稍后再试',
                            showCancel: false,
                        })
                    },
                    complete: () => {
                        wx.hideLoading()
                    }
                })
            }
        )
    },
    //上传视频
    chooseVideo: function (completeFun) {
        let that = this
        wx.chooseVideo({
            sourceType: ['album', 'camera'],
            maxDuration: 60,
            camera: 'back',
            success: function (res) {
                that.uploadfile(res.tempFilePath, function (r) {
                    var data = JSON.parse(r.data)
                    that.getVideoStatus(data.data.id, completeFun)
                    that.uploadRes(data.data.id)
                })
            }
        })
    },
    //uploadfile
    uploadfile: function (file, successFun) {
        wx.showLoading({
            title: '上传中'
        })
        let uploadToken = this.globalData.uploadToken
        wx.uploadFile({
            url: this.globalData.url + 'uploads/uploadfile',
            method: 'POST',
            filePath: file,
            header: {
                'content-type': 'multipart/form-data'
            },
            formData: {
                'uploadToken': uploadToken
            },
            name: 'file',
            success: r => {
                var rcode = JSON.parse(r.data)
                if (rcode.code == 2301) {
                    wx.showModal({
                        title: '提示',
                        content: '上传失败',
                        showCancel: false
                    })
                    wx.hideLoading()
                    return false
                }
                successFun(r)
            },
            fail: r => {
                console.log(r)
                wx.showModal({
                    title: '提示',
                    content: '上传失败' + r,
                    showCancel: false
                })
                wx.hideLoading()
            }
        })
    },
    //检测视频上传是否完成
    getVideoStatus: function (videoId, completeFun) {
        var that = this
        var sign = wx.getStorageSync('sign')
        wx.request({
            url: that.globalData.url + 'teach/getVideoStatus?sign=' + sign + '&videoId=' + videoId,
            success: msg => {
                if (msg.data.code == 200) {
                    if (msg.data.data.status == 0) {
                        setTimeout(function () {
                            that.getVideoStatus(videoId, completeFun)
                        }, 1000)
                    } else {
                        wx.hideLoading()
                        wx.showModal({
                            title: '提示',
                            content: '上传成功',
                            showCancel: false
                        })
                        completeFun()
                    }

                }
            }
        })
    },
    // 上传视频到服务器
    uploadRes: function (videoId) {
        var that = this
        var sign = wx.getStorageSync('sign') || ''
        var activity_id = that.globalData.activity_id
        var user_video_id = that.globalData.user_video_id
        var data = {
            'sign': sign,
            'video_id': videoId,
            'user_video_id': user_video_id,
            'activity_id': activity_id,
        }
        wx.request({
            url: that.globalData.url + '/videolike/addActionVideo?sign=' + sign,
            method: 'POST',
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            data: data,
            success: msg => {
                if (msg.data.code == 200) {
                } else {
                    wx.showModal({
                        title: '提示',
                        content: msg.data.message,
                        showCancel: false
                    })
                }
            },
            fail: () => {
                wx.showModal({
                    title: '提示',
                    content: '服务器错误，请稍后再试',
                    showCancel: false
                })
            },
            complete: () => {

            }
        })
    },
    // 处理点赞数的格式
    testNum:function(num = 0) {
        if (num < 1000) {
            return num;
        }else {
            return Math.round(num / 1000, 2)+'K'
        } 
    },
    // 获取uploadToken
    getUploadToken: function () {
        var that = this;
        var sign = wx.getStorageSync('sign');
        wx.request({
            url: that.globalData.url + 'videolike/getToken?sign=' + sign,
            method: 'POST',
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            success: res => {
                if (res.data.code == 200) {
                    that.globalData.uploadToken = res.data.data.uploadToken
                } else {
                    wx.showModal({
                        title: '提示',
                        content: res.data.message,
                        showCancel: false
                    })
                }
            }
        })
    }
})